package com.xydpeng.tech.order.service.order.statemachine.eventhandler;

import com.alibaba.cola.statemachine.Action;
import com.alibaba.cola.statemachine.Condition;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xydpeng.tech.order.dal.das.OrderDas;
import com.xydpeng.tech.order.dal.das.OrderStateLogDas;
import com.xydpeng.tech.order.dal.entity.Order;
import com.xydpeng.tech.order.dal.entity.OrderStateLog;
import com.xydpeng.tech.order.enums.OrderStatusEnum;
import com.xydpeng.tech.order.service.order.statemachine.OrderContext;
import com.xydpeng.tech.order.service.order.statemachine.OrderEvent;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @version v1.0
 * @author xydpeng
 * @date: 2024/12/18
 * @description:
 */
@Slf4j
@Component
public class PendingToPaidOnPayEventHandler implements EventHandler {
    @Resource
    private OrderDas orderDas;
    @Resource
    private OrderStateLogDas orderStateLogDas;

    @Override
    public Condition<OrderContext> checkCondition() {
        Condition<OrderContext> condition = (ctx) -> {
            orderDas.update(Wrappers.lambdaUpdate(Order.class).set(Order::getPayStatus, 1).eq(Order::getOrderCode, ctx.getOrderCode()));
            return orderDas.updateOrderStatusAtomic(ctx.getOrderCode(), OrderStatusEnum.PENDING, OrderStatusEnum.PAID);
        };
        return condition;
    }

    @Override
    public Action<OrderStatusEnum, OrderEvent, OrderContext> doAction() {
        Action<OrderStatusEnum, OrderEvent, OrderContext> action = (fromStatus, toStatus, event, ctx) -> {
            //记录日志
            OrderStateLog stateLog = new OrderStateLog();
            stateLog.setOrderCode(ctx.getOrderCode());
            stateLog.setFromStatus(fromStatus.getCode());
            stateLog.setToStatus(toStatus.getCode());
            stateLog.setEvent(event.ordinal());
            orderStateLogDas.save(stateLog);
        };
        return action;
    }
}
